﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Packaging;

namespace Note_Final_new
{
    public class Note
    {
        // 标题
        public string Title { get; set; }
        // 内容
        public string Content { get; set; }
        // 创建时间
        public DateTime CreatedTime { get; set; }
        // 修改时间
        public DateTime ModifiedTime { get; set; }
        public string FilePath { get; private set; }
        // 用户名属性
        public string Username;
        public string NotebookPath { get; set; }

        public Note(string username)
        {
            CreatedTime = DateTime.Now;
            ModifiedTime = DateTime.Now;
            Username = username;
        }

        // 设置文件路径
        public void SetFilePath(string path)
        {
            FilePath = path;
        }

        // 保存笔记
        public void Save()
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                string safeTitle = MakeValidFileName(Title);
                FilePath = Path.Combine(
                    NotebookPath,
                    $"{safeTitle}_{CreatedTime:yyyyMMddHHmmss}.rtf" // 默认保存为 RTF
                );
            }

            Directory.CreateDirectory(Path.GetDirectoryName(FilePath));

            string extension = Path.GetExtension(FilePath).ToLower();
            if (extension == ".txt")
            {
                File.WriteAllText(FilePath, Content, Encoding.UTF8);
            }
            else if (extension == ".docx")
            {
                SaveAsWord(FilePath);
            }
            else if (extension == ".rtf")
            {
                File.WriteAllText(FilePath, Content); // 保存为 RTF
            }
            else
            {
                throw new NotSupportedException("不支持的文件格式");
            }

            ModifiedTime = DateTime.Now;
        }

        // 删除笔记
        public void Delete()
        {
            if (File.Exists(FilePath))
            {
                File.Delete(FilePath);
            }
        }

        // 从文件加载笔记
        public static Note LoadFromFile(string filePath)
        {
            string username = Path.GetFileName(Path.GetDirectoryName(filePath));
            var note = new Note(username)
            {
                FilePath = filePath,
                CreatedTime = File.GetCreationTime(filePath),
                ModifiedTime = File.GetLastWriteTime(filePath)
            };

            string extension = Path.GetExtension(filePath).ToLower();
            if (extension == ".txt")
            {
                note.Content = File.ReadAllText(filePath, Encoding.UTF8);
            }
            else if (extension == ".docx")
            {
                note.Content = LoadWordContent(filePath);
            }
            else if (extension == ".rtf")
            {
                note.Content = File.ReadAllText(filePath); // RTF内容直接加载
            }
            else
            {
                throw new NotSupportedException("不支持的文件格式");
            }

            string fileName = Path.GetFileNameWithoutExtension(filePath);
            int lastUnderscore = fileName.LastIndexOf('_');
            note.Title = lastUnderscore > 0 ? fileName.Substring(0, lastUnderscore) : fileName;

            return note;
        }

        // 保存为 Word 文件
        private void SaveAsWord(string filePath)
        {
            try
            {
                using (var wordDocument = WordprocessingDocument.Create(filePath, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
                {
                    var mainPart = wordDocument.AddMainDocumentPart();
                    mainPart.Document = new DocumentFormat.OpenXml.Wordprocessing.Document();
                    var body = new DocumentFormat.OpenXml.Wordprocessing.Body();

                    // 添加标题
                    var titleParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                        new DocumentFormat.OpenXml.Wordprocessing.Run(
                            new DocumentFormat.OpenXml.Wordprocessing.Text(Title))
                    );
                    body.Append(titleParagraph);

                    // 添加内容
                    var contentParagraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(
                        new DocumentFormat.OpenXml.Wordprocessing.Run(
                            new DocumentFormat.OpenXml.Wordprocessing.Text(Content))
                    );
                    body.Append(contentParagraph);

                    mainPart.Document.Append(body);
                    mainPart.Document.Save();
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"保存 Word 文件失败：{ex.Message}", ex);
            }
        }

        // 加载 Word 文件内容
        public static string LoadWordContent(string filePath)
        {
            try
            {
                using (var wordDocument = WordprocessingDocument.Open(filePath, false))
                {
                    var body = wordDocument.MainDocumentPart.Document.Body;
                    return body.InnerText; // 获取文档的纯文本内容
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"加载 Word 文件失败：{ex.Message}");
            }
        }

        // 替换非法字符
        private string MakeValidFileName(string name)
        {
            foreach (char c in Path.GetInvalidFileNameChars())
            {
                name = name.Replace(c, '_');
            }
            return name;
        }
    }
}
